<template>
	<view class="add">
		<form @submit="submitFn" @reset="resetFn">
			<input class="item" v-model="formVal.title" type="text" name="title" placeholder="请输入标题">
			<input class="item" v-model="formVal.author" type="text" name="author" placeholder="请输入作者">
			<textarea class="item" v-model="formVal.content" name="content" placeholder="请输入详细内容"></textarea>
			<uni-file-picker v-model="picArr" limit="9" fileMediatype="image" mode="grid" @success="uploadSuccess"
				@delete="uploadDelete"></uni-file-picker>
			<button class="item" form-type="reset">重置</button>
			<button class="item" :disabled="isDisabled" form-type="submit" type="primary">提交</button>
		</form>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formVal: {
					title: '',
					author: '',
					content: ''
				},
				picArr: [],
				picUrls: []
			}
		},
		methods: {
			// 点击提交
			async submitFn(e) {

				const detail = e.detail.value

				// 清空表单
				this.resetFn()

				const res = await uniCloud.callFunction({
					name: 'art_add_row',
					data: {
						detail,
						picUrls: this.picUrls
					}
				})


				uni.showToast({
					title: '发布成功',
					mask: true
				})
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}, 800)
			},
			// 点击重置
			resetFn() {
				this.formVal.title = ''
				this.formVal.author = ''
				this.formVal.content = ''
			},
			// 图片上传成功
			uploadSuccess(e) {

				this.picUrls = [...this.picUrls, ...e.tempFilePaths]
			},
			uploadDelete(e) {
				const index = this.picUrls.findIndex(item => item === e.tempFilePath)
				this.picUrls.splice(index, 1)

			}
		},
		computed: {
			// 判断按钮是否禁用
			isDisabled() {
				/* for (let key in this.formVal) {
					if (this.formVal[key].length === 0) {

						return true
					}
				}
				return false */
				return Object.keys(this.formVal).some(item => {
					return this.formVal[item].length === 0
				})


			}
		}
	}
</script>

<style lang="scss" scoped>
	.add {
		padding: 30rpx;

		form {

			.item {
				margin-bottom: 20rpx;
			}

			input,
			textarea {

				padding: 0 20rpx;
				border: 1px solid #eee;
			}

			textarea {
				box-sizing: border-box;
				width: 100%;
				height: 200rpx;
			}

			input {
				padding: 20rpx;
			}
		}
	}
</style>